import { message } from "antd";
import { useState, useEffect } from "react";
import { find } from "lodash";
import { useNavigate } from "react-router-dom";
import SelectActions from "../../../../../common/components/SelectAction";
import { updateOrderStatus } from "../../utils/orderStatus";
import { checkOrder, countOrderSum } from "../../utils/checkOrderConfig";
import ActionMap from "../../ActionMap";
import Api from '../../service';
import { Button } from "antd";


//默认样式
const defaultStyle = {
	display: 'inline-block',
	margin: '0 8px 8px 0'
}

const Actions = props => {
	const { searchForm, selectKeys, operationPage, orderList, handleOk } = props;
	const [modalName, setModalName] = useState();
	const [item, setItem] = useState({});
	const navigate = useNavigate();
    const [num, setNum] = useState(0); //查询供应商匹配统计


    useEffect(() => {
        handleGetInfoCount();
	}, [location])

    //查询供应商匹配统计
    const handleGetInfoCount = async () => {
        const { success, data } = await Api.getInfoCount();
        if(success) {
            setNum(data);
        }
    }

	//智能操作，不需要勾选
	const handleAutoOpera = props => {
		const { scene, modalValue, item = {} } = props;
		setItem({
			scene,
			...item
		});
		setModalName(modalValue);
	};

	//点击批量更新状态
	const handleUpdateOrderStatus = props => {
		const { scene, isModal, modalValue, isCheck = true, item = {} } = props;
		//这里需要判断是否选择了数据
		if (selectKeys.length > 0) {
			let checkResult = false,
				countList = [];
			if (isCheck) {
				checkResult = checkOrder(scene, selectKeys, orderList);
				countList = countOrderSum(scene, selectKeys, orderList);
			}

			if (checkResult || !isCheck) {
				if (isModal) {
					setItem({
						scene,
						countList,
						...item
					});
					setModalName(modalValue);
				} else {
					const items = {
						selectKeys,
						orderList
					};
					updateOrderStatus(scene, items, afterUpdate);
				}
			}
		} else {
			message.info("请选择订单");
		}
	};

	//手动拆单
	const handleManualSplitOrder = modalValue => {
		if (selectKeys.length > 0) {
			if (selectKeys.length > 1) {
				return message.info("该操作仅支持勾选一个订单");
			}
			const obj = find(orderList, ["id", selectKeys[0]]);
			if (obj) {
				if (obj.state != 10) {
					return message.info("请勾选待审核订单");
				}
				if (obj.runVolume) {
					return message.info("跑量订单不允许拆单");
				}
				setModalName(modalValue);
			}
		} else {
			message.info("请选择订单");
		}
	};

	//手动合单
	const handleManualMergeOrder = modalValue => {
		if (selectKeys.length > 0) {
			if (selectKeys.length > 1) {
				return message.info("请勾选1个待审核订单进行合单");
			}
			const obj = find(orderList, ["id", selectKeys[0]]);
			if (obj) {
				if (obj.state != 10) {
					return message.info("请勾选1个待审核订单进行合单");
				}
				if (obj.runVolume) {
					return message.info("跑量订单不允许合单");
				}
				setModalName(modalValue);
			}
		} else {
			message.info("请选择订单");
		}
	};

	//更新状态之后的函数
	const afterUpdate = () => {
		//这里处理成功的逻辑
		if(operationPage == 'orderShip') {
			setTimeout(()=>{
				handleOk(2);
			}, 1000)
		} else {
			handleOk();
		}
	};

	//弹框参数
	const ModalProps = {
		item,
		searchForm,
		operationPage,
		selectKeys,
		orderList,
		handleOk(updateType, data) {
			setModalName();
			handleOk(updateType, data);
		},
		handleCancel() {
			setModalName();
			setItem({});
            if(modalName == 'UnmatchedProductDetailsModal') {
                handleGetInfoCount();
            }
		}
	};

	//新增拉取订单配置项
	const makeOrderOptions = [
		{
			label: "手工下单",
			action() {
				setModalName('ManuallyOrdersModal');
			}
		},
		{
			label: "导入订单",
			action() {
				navigate("/views/order/excel");
			}
		},
		{
			label: "手工同步订单",
			action() {
				setModalName('ManuallySyncOrdersModal');
			}
		}
	]

	//快递单号配置项
	const expressOptions = [
		{
			label: "获取面单号",
			action() {
				handleUpdateOrderStatus({ isCheck: false, isModal: true, modalValue: 'GetWaybillNumberModal' });
			}
		},
		{
			label: "批量输入运单号",
			action() {
				handleUpdateOrderStatus({ scene: "batchInputLogisticNo", isModal: true, modalValue: 'BatchInputLogisticNo' });
			}
		},
		{
			label: "清空运单号",
			action() {
				handleUpdateOrderStatus({ isCheck: false, isModal: true, modalValue: 'GetWaybillNumberModal', item: { isClear: true } });
			}
		},
		{
			label: "导入云仓运单号",
			action() {
				handleAutoOpera({ modalValue: 'ImportYuncangOrderModal' });
			}
		},
		{
			label: "云仓单号匹配",
			action() {
				handleAutoOpera({ modalValue: 'MatchYuncangOrderModal' });
			}
		},
	]

	//修改标记的配置项
	const updateOptions = [
		{
			label: "设置标签",
			action() {
				handleUpdateOrderStatus({
					isModal: true,
					isCheck: false,
					modalValue: 'SetOrderLabelModal'
				});
			}
		},
		{
			label: "修改订单备注",
			action() {
				handleUpdateOrderStatus({
					isModal: true,
					isCheck: false,
					modalValue: 'SetOrderNothsModal',
					item: { remarkType: "orderRemark", isBatch: true }
				});
			}
		},
		{
			label: "修改卖家备注",
			action() {
				handleUpdateOrderStatus({
					isModal: true,
					isCheck: false,
					modalValue: 'SetOrderNothsModal',
					item: { remarkType: "sellerMessage", isBatch: true }
				});
			}
		},
		{
			label: "供应商匹配",
			action() {
				handleUpdateOrderStatus({
					isModal: true,
					isCheck: false,
					modalValue: 'SupplierMatchingModal'
				});
			}
		},
		{
			label: "包装或赠品",
			action() {
				handleUpdateOrderStatus({ isModal: true, isCheck: false, modalValue: 'SetPackageAndGiveawayModal' });
			}
		},
		{
			label: "取消运费拦截",
			action() {
				handleUpdateOrderStatus({ isModal: true, isCheck: false, modalValue: 'SetForcedSendGoodsModal' });
			}
		}
	]

	//合并拆分配置项
	const mergeOptiosn = [
		{
			label: "手动拆单",
			action() {
				handleManualSplitOrder('SplitOrderModal');
				// handleUpdateOrderStatus({ scene: "manualSplitOrder", isModal: true, isCheck: true, isSingle: true, modalValue: 'SplitOrderModal' });
			}
		},
		{
			label: "按照策略拆单",
			action() {
				handleAutoOpera({
					scene: "autoSplitOrder",
					item: { selectKeys, orderList, searchForm },
					modalValue: 'IntelligentSplittingStrategy'
				});
			}
		},
		{
			label: "手动合单",
			action() {
				handleManualMergeOrder('MergeOrdersModal');
			}
		},
		{
			label: "智能合单",
			action() {
				handleAutoOpera({ scene: "autoMergeOrder", modalValue: 'IntelligentMergeOrdersModal' });
			}
		}
	]

	//跑量配置项
	const runVolumeOptions = [
		{
			label: "设跑量",
			action() {
				handleUpdateOrderStatus({ isModal: true, isCheck: false, modalValue: 'SetRunVolumeModal' });
			}
		},
		{
			label: "取消跑量",
			action() {
				handleUpdateOrderStatus({ isModal: true, isCheck: false, modalValue: 'CancelRunVolumeModal' });
			}
		}
	]

	//导出配置项
	const exportOptions = [
		{
			label: "按勾选订单导出",
			action() {
				handleUpdateOrderStatus({
					isModal: true,
					isCheck: false,
					item: { isBatch: true, taskType: 2004 },
					modalValue: 'ExportTelCodeModal'
				});
			}
		},
		{
			label: "按查询订单导出",
			action() {
				if (orderList.length) {
					handleAutoOpera({
						item: { isBatch: false, taskType: 2004 },
						modalValue: 'ExportTelCodeModal'
					});
				} else {
					message.info("暂无可导出的数据！");
				}
			}
		},
		{
			label: "维护导出表字段信息",
			action() {
				// handleUpdateOrderStatus({ isModal: true, isCheck: false, modalValue: 'ExportOrderExcelModal' });
				setModalName('ExportOrderExcelModal');
			}
		}
	]

	//策略配置
	const strageryOptions = [
		{
			label: "智能策略手动执行",
			action() {
				handleAutoOpera({
					scene: "manualExecute",
					item: { selectKeys, orderList, searchForm },
					modalValue: 'ManualExecute'
				});
			}
		},
		{
			label: "智能策略自动执行",
			action() {
				handleAutoOpera({
					scene: "autoExecute",
					item: { selectKeys, orderList, searchForm },
					modalValue: 'AutoExecute'
				});
			}
		}
	]

	// 批量换货
	const productEditOptions = [
		{
			label: "修改商品",
			action: () => handleUpdateOrderStatus({ scene: "modifyGoods", isModal: true, modalValue: 'UpdateGoodsModal' })
		},
		{
			label: "批量换货",
			action() {
				handleUpdateOrderStatus({ scene: "modifyGoods", isModal: true,  modalValue: 'UpdateGoodsSwitchModal' });
			}
		}
	]

	const actionArr = [
		{ name: '订单审核', type: 'primary', action: () => handleUpdateOrderStatus({ scene: "vertifyOrder" }) },
		{ name: '新增/拉取订单', options: makeOrderOptions },
		{ name: `未匹配商品明细`, action: () => setModalName('UnmatchedProductDetailsModal') },
		// { name: "修改商品3", action: () => handleUpdateOrderStatus({ scene: "modifyGoods", isModal: true, modalValue: 'UpdateGoodsModal' }) },
		{ name: "修改商品", options: productEditOptions },
		{ name: '修改发货仓', action: () => handleUpdateOrderStatus({ isCheck: false, isModal: true, modalValue: 'SelectShippingWarehouseModal' }) },
		{ name: '修改快递', action: () => handleUpdateOrderStatus({ scene: "modifyExpress", isModal: true, modalValue: 'SetExpressModal' }) },
		{ name: '快递单号', options: expressOptions },
		{ name: '转异常', action: () => handleUpdateOrderStatus({ scene: "abnormalOrder", isModal: true, modalValue: 'SetOrderStatusForErrorModal' }) },
		{ name: '转正常单', action: () => handleUpdateOrderStatus({ scene: "normalOrder", isModal: true, modalValue: 'SetOrderStatusForNormalModal' }) },
		{ name: '作废订单', action: () => handleUpdateOrderStatus({ scene: "voidOrder", isModal: true, modalValue: 'VoidOrderModal' }) },
		{ name: '修改/标记', options: updateOptions },
		{ name: '合并/拆分', options: mergeOptiosn },
		{ name: '跑量', options: runVolumeOptions },
		{
			name: '物流回传', action: () => handleUpdateOrderStatus({
				scene: "logisticReturn",
				isModal: true,
				isCheck: false,
				item: { searchForm },
				modalValue: 'LogisticsBackhaulModal'
			})
		},
		{ name: '智能策略', options: strageryOptions },
		{ name: '订单重算', action: () => handleUpdateOrderStatus({ isCheck: false,  isModal: true, modalValue: 'WeightRecalculation' }) },
		{ name: '导出订单', options: exportOptions },
	]

	return (
		<>
			{modalName && <ActionMap modalName={modalName} ModalProps={ModalProps} />}
			{
				actionArr.map(v => {
                    if(v.name == '未匹配商品明细') {
                        return <Button onClick={v.action} style={{height: '28px', fontSize: '12px', marginRight: '8px'}}>未匹配商品明细（<span className="common-color9">{num}</span>）</Button>
                    }
					return (
						<SelectActions
							style={defaultStyle}
							key={v.name}
							name={v.name}
							type={v.type}
							options={v.options || []}
							onClick={v.action}
						/>
					)
				})
			}
		</>
	);
};
export default Actions;
